package com.aids_malaria.ui;

import android.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.aids_malaria.R;
import com.aids_malaria.app.AppManager;
import com.aids_malaria.app.Constant;
import com.aids_malaria.base.BaseActivity;
import com.aids_malaria.db.DBManager;
import com.aids_malaria.event.Events;
import com.aids_malaria.http.BaseObserver;
import com.aids_malaria.http.RetrofitFactory;
import com.aids_malaria.http.RxScheduler;
import com.aids_malaria.http.api.RetrofitApi;
import com.aids_malaria.http.response.AppUpdate;
import com.aids_malaria.http.response.LoginUserAuth;
import com.aids_malaria.ui.datacollect.DataCollectFragment;
import com.aids_malaria.ui.report.ReportFragment;
import com.aids_malaria.ui.setting.SettingFragment;
import com.aids_malaria.util.AppUtil;
import com.aids_malaria.util.DisplayUtil;
import com.aids_malaria.util.SpUtil;
import com.aids_malaria.util.ToastUtil;
import com.aids_malaria.widget.dialog.ConfirmDialog;
import com.king.app.updater.AppUpdater;
import com.luck.picture.lib.rxbus2.Subscribe;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class MainActivity extends BaseActivity {

    @BindView(R.id.fl_content)
    FrameLayout fl_content;
    @BindView(R.id.tv_setting)
    TextView tv_setting;
    @BindView(R.id.tv_data_get)
    TextView tv_data_get;
    @BindView(R.id.tv_count_report)
    TextView tv_count_report;
    @BindView(R.id.tv_user_name)
    TextView tv_user_name;

    public static final int INDEX_SETTING = 0;
    public static final int INDEX_DATA_COLLECT = 1;
    public static final int INDEX_REPORT = 2;

    private int currentIndex = 1;

    private SettingFragment mSettingFragment;
    private DataCollectFragment mDataCollectFragment;
    private ReportFragment mReportFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取用户当前的角色
        if (SpUtil.getBoolean(mContext,Constant.IS_LOGIN,false)){
            getUserRole();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        switchToFragment(INDEX_DATA_COLLECT);
        tv_user_name.setText(SpUtil.getString(mContext, Constant.USER_ACCOUNT_NAME, "Name"));
        appUpdate();
    }

    @OnClick({R.id.tv_data_get, R.id.tv_setting, R.id.tv_count_report, R.id.ll_account_info})
    public void onClick(View view) {
        switch (view.getId()) {
            /**
             * 用户管理（010101）
             * 角色管理（010102）
             * 工作区域设置（010103）
             * PAD序号设置（010104）
             * 人员采集数据上传下载（010105）
             * 行政村相关数据上传下载（010106）
             * 人员基本数据采集（010201）
             * 诊疗-诊断数据采集（010202）
             * 诊疗-检验数据采集（010203）
             * 诊疗-药物治疗数据采集（010204）
             * 诊疗-感染来源调查数据采集（010205）
             * 诊疗-疫源处理数据采集（010206）
             * 诊疗-人员采集数据查询（010207）
             * 行政村数据采集（010208）
             * 蚊媒数据采集（010209）
             * 人员数据统计（010301）
             * 蚊媒数据统计（010302）
             */

            case R.id.tv_setting:
                // 设置
                switchToFragment(INDEX_SETTING);
                break;
            case R.id.tv_data_get:
                // 数据采集
                switchToFragment(INDEX_DATA_COLLECT);
                break;
            case R.id.tv_count_report:
                // 统计报告
                switchToFragment(INDEX_REPORT);
                break;
            case R.id.ll_account_info:
                ConfirmDialog.newInstance(true, getString(R.string.hint), getString(R.string.hint_logout))
                        .setCancelConfirOption(new ConfirmDialog.CancelConfirOption() {
                            @Override
                            public void cancel() {

                            }

                            @Override
                            public void confirm() {
                                checkIsHasDataUpload();
                            }
                        })
                        .setOutCancel(true)
                        .setWidth(DisplayUtil.px2dp((int) (DisplayUtil.getWindowWidth() * 0.5)))
                        .show(getSupportFragmentManager());
                break;
            default:
                break;
        }
    }

    /**
     * 检查是否有数据未上传
     */
    private void checkIsHasDataUpload() {
        int unUpLoadCount = DBManager.get().personDataDao().getAllByCreateUpdate(true).size() +
                DBManager.get().diagnosisInfoPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().eaProcessPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().getMedicalTreatmentPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().drugallergyInfoPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().premedicalTreatmentPackDao().getAllByCreateUpdate(true).size() +
                DBManager.get().areaVDao().getAllByCreateUpdate(true).size() +
                DBManager.get().mosquitoInvestDao().getAllByCreateUpdate(true).size();
        if(unUpLoadCount>0){
            ConfirmDialog.newInstance(true, getString(R.string.hint), getString(R.string.has_data_not_upload_sure_logout))
                    .setCancelConfirOption(new ConfirmDialog.CancelConfirOption() {
                        @Override
                        public void cancel() {

                        }

                        @Override
                        public void confirm() {
                            String userCode = SpUtil.getString(mContext, Constant.USER_ACCOUNT, "");
                            String password = SpUtil.getString(mContext, Constant.USER_PASSWORD, "");
                            String deviceId = AppUtil.getDeviceId(mContext);
                            logout(userCode, deviceId, password);
                        }
                    })
                    .setOutCancel(true)
                    .setWidth(DisplayUtil.px2dp((int) (DisplayUtil.getWindowWidth() * 0.5)))
                    .show(getSupportFragmentManager());
        }else{
            String userCode = SpUtil.getString(mContext, Constant.USER_ACCOUNT, "");
            String password = SpUtil.getString(mContext, Constant.USER_PASSWORD, "");
            String deviceId = AppUtil.getDeviceId(mContext);
            logout(userCode, deviceId, password);
        }
    }

    /**
     * 获取权限
     */
    private void getUserRole(){
        RetrofitFactory.getInstance().createApi(RetrofitApi.class).getUserAUTH()
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new BaseObserver<List<LoginUserAuth>>(){

                    @Override
                    protected void onStart() {

                    }

                    @Override
                    protected void onSuccess(List<LoginUserAuth> data) throws Exception {
//                        Log.d("1","用户的权限" + GsonUtil.beanToJson(data));
                        DBManager.get().loginUserAuthDao().deleteAll();
                        DBManager.get().loginUserAuthDao().insertAll(data);
                    }

                    @Override
                    protected void onFinish() {

                    }
                });
    }

    /**
     * 退出登录
     * @param userCode
     * @param padId
     * @param password
     */
    private void logout(String userCode, String padId, String password) {
        if(isOnLine()){
            RetrofitFactory.getInstance().createApi(RetrofitApi.class).logout(userCode, padId, password)
                    .compose(RxScheduler.rxSchedulerTransform())
                    .subscribe(new BaseObserver<Object>() {

                        @Override
                        protected void onStart() {
                            getLoadingDialog().show();
                        }

                        @Override
                        protected void onSuccess(Object data) throws Exception {
                            //清除登录信息
                            //SpUtil.getBoolean(mContext,Constant.IS_REMEMBER_ACCOUNT,false);
                            SpUtil.putBoolean(mContext, Constant.IS_LOGIN, false);
                            SpUtil.putString(mContext, Constant.TOKEN, "");
                            if (!SpUtil.getBoolean(mContext, Constant.IS_REMEMBER_ACCOUNT, false)) {
                                SpUtil.putString(mContext, Constant.USER_ACCOUNT, "");
                                SpUtil.putString(mContext, Constant.USER_ACCOUNT_NAME, "");
                            }
                            SpUtil.putString(mContext, Constant.USER_PASSWORD, "");
                            SpUtil.putString(mContext, Constant.PAD_SEQ, "");
                            startActivity(LoginActivity.class);
                            AppManager.getInstance().finishAllActivityExcept(LoginActivity.class);
                        }

                        @Override
                        protected void onFinish() {
                            getLoadingDialog().dismiss();
                        }
                    });
        }else{
            //清除登录信息
            //SpUtil.getBoolean(mContext,Constant.IS_REMEMBER_ACCOUNT,false);
            SpUtil.putBoolean(mContext, Constant.IS_LOGIN, false);
            SpUtil.putString(mContext, Constant.TOKEN, "");
            if (!SpUtil.getBoolean(mContext, Constant.IS_REMEMBER_ACCOUNT, false)) {
                SpUtil.putString(mContext, Constant.USER_ACCOUNT, "");
                SpUtil.putString(mContext, Constant.USER_ACCOUNT_NAME, "");
            }
            SpUtil.putString(mContext, Constant.USER_PASSWORD, "");
            SpUtil.putString(mContext, Constant.PAD_SEQ, "");
            startActivity(LoginActivity.class);
            AppManager.getInstance().finishAllActivityExcept(LoginActivity.class);
        }
    }

    /**
     * 切换tab
     * @param index
     */
    private void switchToFragment(int index) {
        selectTab(index);
        currentIndex = index;
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        switch (index) {
            case INDEX_SETTING:
                if (null == mSettingFragment) {
                    mSettingFragment = SettingFragment.getInstance();
                    fragmentTransaction.add(R.id.fl_content, mSettingFragment);
                }
                if (null != mDataCollectFragment) {
                    fragmentTransaction.hide(mDataCollectFragment);
                }
                if (null != mReportFragment) {
                    fragmentTransaction.hide(mReportFragment);
                }
                fragmentTransaction.show(mSettingFragment);
                fragmentTransaction.commitAllowingStateLoss();
                break;
            case INDEX_DATA_COLLECT:
                if (null == mDataCollectFragment) {
                    mDataCollectFragment = DataCollectFragment.getInstance();
                    fragmentTransaction.add(R.id.fl_content, mDataCollectFragment);
                }
                if (null != mSettingFragment) {
                    fragmentTransaction.hide(mSettingFragment);
                }
                if (null != mReportFragment) {
                    fragmentTransaction.hide(mReportFragment);
                }
                fragmentTransaction.show(mDataCollectFragment);
                fragmentTransaction.commitAllowingStateLoss();
                break;
            case INDEX_REPORT:
                if (null == mReportFragment) {
                    mReportFragment = ReportFragment.getInstance();
                    fragmentTransaction.add(R.id.fl_content, mReportFragment);
                }
                if (null != mSettingFragment) {
                    fragmentTransaction.hide(mSettingFragment);
                }
                if (null != mDataCollectFragment) {
                    fragmentTransaction.hide(mDataCollectFragment);
                }
                fragmentTransaction.show(mReportFragment);
                fragmentTransaction.commitAllowingStateLoss();
                break;
            default:
                break;
        }

    }

    private void selectTab(int index) {
        tv_setting.setTextColor(getResources().getColor(R.color.c_black));
        tv_data_get.setTextColor(getResources().getColor(R.color.c_black));
        tv_count_report.setTextColor(getResources().getColor(R.color.c_black));
        switch (index) {
            case INDEX_SETTING:
                tv_setting.setTextColor(getResources().getColor(R.color.c_app_blue));
                break;
            case INDEX_DATA_COLLECT:
                tv_data_get.setTextColor(getResources().getColor(R.color.c_app_blue));
                break;
            case INDEX_REPORT:
                tv_count_report.setTextColor(getResources().getColor(R.color.c_app_blue));
                break;
            default:
                break;
        }
    }

    /**
     * token过期回调
     * @param overTokenEvent
     */
    @Subscribe
    public void onCodeEvent(Events.OverTokenEvent overTokenEvent) {
        //清除登录信息
        //SpUtil.getBoolean(mContext,Constant.IS_REMEMBER_ACCOUNT,false);
        SpUtil.putBoolean(mContext, Constant.IS_WORK_MODEL_ON_LINE,true);
        SpUtil.putBoolean(mContext, Constant.IS_LOGIN, false);
        SpUtil.putString(mContext, Constant.TOKEN, "");
        if (!SpUtil.getBoolean(mContext, Constant.IS_REMEMBER_ACCOUNT, false)) {
            SpUtil.putString(mContext, Constant.USER_ACCOUNT, "");
            SpUtil.putString(mContext, Constant.USER_ACCOUNT_NAME, "");
        }
        SpUtil.putString(mContext, Constant.USER_PASSWORD, "");
        startActivity(LoginActivity.class);
        AppManager.getInstance().finishAllActivityExcept(LoginActivity.class);
    }

    /**
     * 版本更新
     */
    private void appUpdate() {
        RetrofitFactory.getInstance().createApi("http://api.bq04.com/", RetrofitApi.class).
                appUpdate("0a68aa7bb9e736cb1ed2fd170fbe45e2")
                .compose(RxScheduler.rxSchedulerTransform())
                .subscribe(new Observer<AppUpdate>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(AppUpdate appUpdate) {
                        if (Integer.valueOf(appUpdate.getVersion()) > AppUtil.getVersionCode(mContext)) {
                            ConfirmDialog.newInstance(true, getString(R.string.hint), getString(R.string.found_new_version_is_update))
                                    .setCancelConfirOption(new ConfirmDialog.CancelConfirOption() {
                                        @Override
                                        public void cancel() {

                                        }

                                        @Override
                                        public void confirm() {
                                            new AppUpdater(mContext, appUpdate.getInstallUrl()).start();
                                        }
                                    })
                                    .setOutCancel(true)
                                    .setWidth(DisplayUtil.px2dp((int) (DisplayUtil.getWindowWidth() * 0.5)))
                                    .show(getSupportFragmentManager());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private long exitTime = 0;
//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//            //两秒之内按返回键就会退出
//            if ((System.currentTimeMillis() - exitTime) > 2000) {
//                if (currentIndex == 1 ){
//                    if (mDataCollectFragment.sholdBackPage()){
//                        mDataCollectFragment.backPage();
//                        return true;
//                    }
//
//                }
//                ToastUtil.showToast(getString(R.string.exist_app));
//                exitTime = System.currentTimeMillis();
//            } else {
//                finish();
//                System.exit(0);
//            }
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }

}
